package com.tanger.im.service.record;

import com.alibaba.fastjson.JSONObject;
import com.tanger.common.exception.AbstractController;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.JSON;
import com.tanger.common.utils.StringUtil;
import com.tanger.im.CacheKey;
import com.tanger.im.entity.IMQuery;
import com.tanger.im.entity.ImUserRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Description 用户控制层
 * @Author Hchenbin
 * @Date 2022/8/1 9:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/tanger/api/im/user:record")
@Api(value = "IM:IM用户:聊天记录",tags="IM:IM用户:聊天记录")
public class IMUserRecordController extends AbstractController{

    @Autowired
    private IMUserRecordService service;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiImplicitParam(name = "userId", value = "IM用户ID", required = true, paramType = "query", dataType = "Long")
    @ApiOperation(value = "聊天记录窗口列表")
    @GetMapping("/findAll")
    public ActionResult<List<ImUserRecord>> findAll(@RequestParam Long userId){
        if (StringUtil.isNull(userId)) {
            return ActionResult.buildResultError("参数缺失");
        }
        String key = String.format(CacheKey.IM_USER_RECORD_LIST, userId);
        String chche = stringRedisTemplate.opsForValue().get(key);
        if (StringUtil.isNull(chche)) {
            List<ImUserRecord> records = service.findAll(userId);
            stringRedisTemplate.opsForValue().set(key, JSON.stringify(records));
            return ActionResult.buildResultSuccess(records);
        } else {
            return ActionResult.buildResultSuccess(JSONObject.parseArray(chche,ImUserRecord.class));
        }
    }

    @ApiOperation(value = "单聊记录详情")
    @PostMapping("/find-one")
    public ActionResult findOne(@RequestBody IMQuery query){
        if (Objects.isNull(query)
                || StringUtil.isNull(query.getFuId()) || StringUtil.isNull(query.getTuId())) {
            return ActionResult.buildResultError("参数缺失");
        }
        return ActionResult.buildResultSuccess(service.findOne(query));
    }

    @ApiOperation(value = "群聊记录详情")
    @PostMapping("/find-group")
    public ActionResult findGroup(@RequestBody IMQuery query){
        if (Objects.isNull(query)
                || StringUtil.isNull(query.getFuId()) || StringUtil.isNull(query.getGroupId())) {
            return ActionResult.buildResultError("参数缺失");
        }
        return ActionResult.buildResultSuccess(service.findGroup(query));
    }
}

